import { Mediapipe } from '@/mediapipe'
import { FaceLandmarker, type NormalizedLandmark } from '@mediapipe/tasks-vision'
import { SceneManager } from '@/scene'
import { transformLandamks } from '@/try-on/landmarks_helps'
import type { Options } from '@/try-on/config'
export class TryOn {
  static #mediapipe: Mediapipe
  static scene: SceneManager
  static #mediapipeDetect?: FaceLandmarker
  static #options: Options
  static async init(canvas: HTMLCanvasElement, options: Options) {
    this.#options = options

    this.#mediapipe = new Mediapipe(this.#options)
    this.scene = new SceneManager(canvas, this.#options)
    // this.renderVideo()
    this.#detect()
    this.#loadMediapipe()
    // this.scene.videoElement.requestVideoFrameCallback(this.detect.bind(this))
  }
  static #flipLandmarks(landmarks: NormalizedLandmark[]) {
    return landmarks.map((l) => ({
      x: 1 - l.x,
      y: l.y,
      z: l.z,
      visibility: l.visibility,
    }))
  }
  static async #loadMediapipe() {
    this.#mediapipeDetect = (await this.#mediapipe.mediapipe)!
  }
  static #detect() {
    if (TryOn.scene.background?.canvas.width && this.#mediapipeDetect) {
      const data = this.#mediapipeDetect?.detectForVideo(
        this.scene.background.canvas,
        performance.now(),
      )
      const landmarks = transformLandamks(data!.faceLandmarks[0])
      this.scene.onLandmarks(landmarks)
    }
    this.scene.animate()
    this.scene.videoElement.requestVideoFrameCallback(TryOn.#detect.bind(TryOn))
  }
  static async onProgress(callback: (progress: number) => void) {
    this.#mediapipe.onProgress(callback)
  }
  static updateOption(option: Options) {
    this.#options = option
  }
}
